const STORAGE_PREFIX = 'USE_GLOBAL_STATE_';
const storageData = {};

/**
 * 对state进行格式化
 * @param {*} storage 
 */
function initStorageData(storage) {
    const { keys = [] } = storage || {};
    const now = new Date().getTime();
    for (let i = 0; i < keys.length; i++) {
        let key = keys[i];
        if (key.indexOf(STORAGE_PREFIX) === 0) {
            let value = wx.getStorageSync(key);
            try {
                value = JSON.parse(value);
                if (!value.timeout || now - value.time < value.timeout) {
                    let storageKey = key.substring(STORAGE_PREFIX.length);
                    storageData[storageKey] = value.state;
                } else {
                    wx.removeStorageSync(key);
                }
            } catch (e) { }
        }
    }
}

//初始化一次
initStorageData(wx.getStorageInfoSync());

//设置缓存位置，及过期时间
const defaultOptions = {
    storage: null, //local
    storageTimeout: 0
};

//获取全局数据
function getGlobalState(name) {
    return storageData[name];
}

function setGlobalState(name, state, options = {}) {
    storageData[name] = state;
    if (options.storage === 'local') {
        wx.setStorageSync(STORAGE_PREFIX + name, JSON.stringify({
            state,
            timeout: options.storageTimeout,
            time: new Date().getTime(),
        }));
    }
}

module.exports = (defaultState, key, options) => {
    if (typeof key === 'undefined' && typeof options === 'undefined') {
        key = defaultState;
        defaultState = undefined;
    } else if (typeof key === 'object' && typeof options === 'undefined') {
        options = key;
        key = defaultState;
        defaultState = undefined;
    }

    options = {
        ...defaultOptions,
        ...options,
    };

    const getState = () => {
        return getGlobalState(key);
    }

    // let state = getState();

    const setState = (newState) => {
        setGlobalState(key, newState, options);
        // state = newState;
    };

    return [getState, setState];
};
